package com.lishe.lishe.lishe.module.mall.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.giftnote.activity.GiftNoteActivity;
import com.lishe.lishe.lishe.module.mall.adapter.MyPagerAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.category.Category;
import com.lishe.lishe.lishe.module.mall.bean.category.CategoryDetail;
import com.lishe.lishe.lishe.module.mall.fragment.MallOtherGoodsFragment;
import com.lishe.lishe.lishe.module.mall.fragment.MallAllGoodsFragment;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.mall.http.MallHttpHelper;
import com.lishe.lishe.lishe.module.mall.view.SearchBarView;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShoppingCartActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by zhcase on 2017/9/12.
 * 商城住模块
 */

public class MallActivity extends BaseActivity implements View.OnClickListener {

    private final static String TAG = MallActivity.class.getSimpleName();
    private EditText mSearchView;
    private View mall_search_panel, mall_index_panel, search_container;
    private SearchBarView search_bar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private MyPagerAdapter mallPagerAdapter;
    private LinkedList<String> titles = new LinkedList<>();
    private LinkedList<Fragment> fragments = new LinkedList<>();
    private LinkedList<Category> categorys = new LinkedList<>();
    private int mallType = Globals.MALL_TYPE_ALL;

    private ImageView goods_cart;
    private TextView goods_count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mall);
        initView();
        setListener();
        MallHttpHelper.getStoreHomeCategoryList(callBackCategorys);
    }

    private void setListener() {
        mSearchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

        mSearchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                Log.e(TAG, "onFocusChange:" + b);
                if (b) {
                    mSearchView.clearFocus();
                    mall_search_panel.setVisibility(View.VISIBLE);
                    mall_index_panel.setVisibility(View.INVISIBLE);
                    search_bar.requestEditFocus();
                    search_bar.setOnButton(new Runnable() {
                        @Override
                        public void run() {

                            mall_search_panel.setVisibility(View.INVISIBLE);
                            mall_index_panel.setVisibility(View.VISIBLE);
                            ((View) mSearchView.getParent()).setFocusable(true);
                            ((View) mSearchView.getParent()).setFocusableInTouchMode(true);
                            ((View) mSearchView.getParent()).requestFocus();
                        }
                    });
                } else {
//                    search_container = (View) findViewById(R.id.search_container);
//                    search_container.requestFocus();
//                    mall_search_panel.setVisibility(View.INVISIBLE);

                }
            }
        });

        //这是覆盖在最上面面的搜索
        search_bar.getEditTextSearch().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Log.e(TAG, "mSearchView" + "IME_ACTION_SEARCH");

                    // 先隐藏键盘
                    ((InputMethodManager) mSearchView.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(MallActivity.this
                                            .getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    // 搜索中。。。
                    Log.e(TAG, "传递参数并进到搜索界面");
                    // 搜索中。。。
                    String keywords=search_bar.getEditTextSearch().getText().toString().trim();
                    if(TextUtils.isEmpty(keywords)){
                        return false;
                    }
                    mall_search_panel.setVisibility(View.GONE);
                    mall_index_panel.setVisibility(View.VISIBLE);
                    MallSearchActivity.jump(MallActivity.this,keywords);
                    return true;
                }

                return false;
            }
        });

    }

    private void initView() {
        mSearchView = (EditText) findViewById(R.id.search_view);
        mall_search_panel = (View) findViewById(R.id.mall_search_panel);
        mall_index_panel = (View) findViewById(R.id.mall_index_panel);
        search_container = (View) findViewById(R.id.search_container);
        search_bar = (SearchBarView) findViewById(R.id.search_bar);
        TextView search_view_hint = (TextView) findViewById(R.id.search_view_hint);
        goods_cart = findViewById(R.id.goods_cart);
        goods_count = findViewById(R.id.goods_count);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        search_view_hint.setText("搜索心意商城");
        goods_cart.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.goods_cart:
                ShoppingCartActivity.jump(MallActivity.this, true);
                break;
        }
    }

    /**
     * 初始化各个模块商城的数据
     */
    private void initFragment() {
        fragments.clear();
        mallPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments, titles);
        for (int i = 0; i < categorys.size(); i++) {
            if (i == 0) {
                fragments.add(MallAllGoodsFragment.newInstance(categorys.get(i)));
            } else {
                fragments.add(MallOtherGoodsFragment.newInstance(categorys.get(i)));
            }
        }
        viewPager.setAdapter(mallPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(mallType);
    }

    LSWebHelper.WebCallBack callBackCategorys = new LSWebHelper.WebCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            Log.e(TAG, "catesdataString:" + dataString);
            categorys.clear();
            List<Category> cates0 = JSON.parseArray(dataString, Category.class);
            categorys.addAll(cates0);
            titles.clear();
            for (Category c : cates0) {
                titles.add(c.getTitle());
            }
            if (cates0.size() >= 0) {
                initFragment();
                MallHttpHelper.getStoreHomeCategoryData(0, callBackCategoryDetail);//0:全部
            }
        }

        @Override
        public void onFailure(String message) {
            Toast.makeText(MallActivity.this, message, Toast.LENGTH_SHORT);
        }
    };

    LSWebHelper.WebCallBack callBackCategoryDetail = new LSWebHelper.WebCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            CategoryDetail cateDetail = (CategoryDetail) JSON.parseObject(dataString, CategoryDetail.class);
        }

        @Override
        public void onFailure(String message) {
            Toast.makeText(MallActivity.this, message, Toast.LENGTH_SHORT);
        }
    };

    private void getGoodsCount() {
        HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
    }

    /**
     * 商品数量
     */
    AsyncHttpResponseHandler getGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("购物车商品数量", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject data=json.optJSONObject("data");
                    int num=data.optInt("num");
                    if (num>0){
                        goods_count.setText(num+"");
                        goods_count.setVisibility(View.VISIBLE);
                    }else{
                        goods_count.setVisibility(View.GONE);
                    }
                } else {
                    goods_count.setVisibility(View.GONE);
                    LoadingUtils.closeDialog();
                    JSONObject msgObject = json.optJSONObject("msg");
                    String msgString = StringUtils.unicodeToString("msg",msgObject.toString());
                    Log.e("商品",""+msgString);
                    if(msgString!=null&&msgString.contains("请登录")){
                        toast("还未登录，无法获取购物车信息！");
                    }else{
                        toast(msgString);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if(!LSWebHelper.getInstance().isUserLogined()){
            goods_cart.setVisibility(View.GONE);
        }else{
            goods_cart.setVisibility(View.VISIBLE);
            getGoodsCount();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, com.lishe.lishe.lishe.module.giftnote.activity.GiftNoteActivity.class);
        activity.startActivity(intent);
    }

}
